package com.project.platformcommon.kafka;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.project.platformcommon.Bean.EmailBean;
import com.project.platformcommon.config.kafka.KafkaConfig;
import com.project.platformcommon.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EmailProducer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private KafkaConfig kafkaConfig;

    private Producer<String, Object> producer;

    private static Gson gson = new GsonBuilder().create();


    public void sendVerCodeProducer(EmailBean emailBean) {
        producer = new KafkaProducer<String, Object>(kafkaConfig.producerConfigs());

        producer.send(new ProducerRecord<String, Object>(Constants.EMAIL_TOPIC, gson.toJson(emailBean)), new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (metadata != null) {
                    log.info("生产消息成功{},验证码{},checksum：{},offset:{},partition:{},topic:{}", emailBean.getRecipient(),emailBean.getVerCode(),metadata.checksum(), metadata.offset(), metadata.partition(), metadata.topic());
                }
                if (exception != null) {
                    log.info("生产消息失败{}", exception.getMessage());
                }
            }
        });
        producer.close();
    }
}
